package org.example.day06;

/**
 * 第二章节:2.3.3.2: volatile关键字之前的代码可以重排
 *      例子:
 *          a = 1;
 *          c = 101;
 *          x = b;
 *          d = 102; //volatile修饰,a,c,x的赋值还会出现指令重排序
 **/
public class MyThread11 {
    private static long x = 0;
    private static long y = 0;
    private static long a = 0;
    private static long b = 0;
    private static long c = 0;
    volatile private static long d = 0;
    private static long e = 0;
    volatile private static long f = 0;

    private static long count = 0;

    public static void main(String[] args) throws InterruptedException {
        for (;;){
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            c = 0;
            d = 0;
            e = 0;
            f = 0;
            count++;
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    a = 1;
                    c = 101;
                    x = b;
                    d = 102; //volatile修饰,a,c,x的赋值还会出现指令重排序
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    e = 201;
                    y = a;
                    f = 202; //volatile修饰,a,c,x的赋值还会出现指令重排序
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            String showStr = "count=" + count + " " + x + "," + y;
            if(x == 0 && y == 0){
                System.err.println(showStr);
                break;
            }else{
                //正常情况下会出现 (x,y) = (1,0) or (1,1) or (0,1),指令重排序后会出现(0,0).
                System.out.println(showStr);
            }
        }
    }
}